<template>
  <div class="department-container">
    <div class="app-container">
      <pageTool>
        <!-- 插入left -->
        <template #left>
          总记录数：{{ total }}条
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button v-allow="'import_emp'" type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button v-allow="'export_emp'" type="danger" size="small" @click="expendFn">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </pageTool>
      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'workNumber'}">
          <el-table-column label="序号" prop="page" />
          <el-table-column label="头像" prop="staffPhoto">
            <template slot-scope="scope">
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template slot-scope="scope">
              形式：{{ format(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" sortable />
          <el-table-column label="入职时间" prop="timeOfEntry" :sortable="true">
            <!-- 添加插件来处理返回的时间数据 -->
            <template slot-scope="scope">
              {{ scope.row.timeOfEntry.slice(0,10) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="AddRoles(scope.row.id)">分配角色</el-button>
              <el-button v-allow="'del_emp'" type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="total,sizes,prev, pager, next,jumper" :total="total" :page-size="size" :current-page.sync="curPage" :page-sizes="[2,5,10,30]" @current-change="hCurrentChange" @size-change="hSizeChange" />
        </el-row>
      </el-card>
    </div>
    <!-- 弹窗组件 -->
    <el-dialog title="新增员工" :visible.sync="showDialog" :close-on-click-modal="false" :close-on-press-escape="false" @close="hCloseDialog">
      <addorEdit ref="AddEmployee" @close="showDialog=false" @update-empolyee="hUpdate" />
    </el-dialog>
    <!-- 弹窗组件 -->
    <el-dialog title="分配角色" :visible.sync="RoleshowDialog" :close-on-click-modal="false" :close-on-press-escape="false">
      <assignRole :id="curId" ref="assignRole" @close="RoleshowDialog=false" @on-success="hUpdateRoleSuccess" />
    </el-dialog>
  </div>
</template>

<script>
// 引入枚举文件
import EmployeeEnum from '@/constant/employees'
console.log('聘用形式', EmployeeEnum.hireType)
// const EmployFormatMap = EmployeeEnum.hireType.reduce((acc, cur) => (acc[cur.id] = cur.value), {})
// 数组转化为对象
const EmployFormatMap = EmployeeEnum.hireType.reduce((acc, cur) => {
  const key = cur.id
  const value = cur.value
  acc[key] = value
  return acc
}, {})
console.log(EmployFormatMap)
// 引入获取数据接口
import { getEmployeeList, delEmployee } from '@/api/employees.js'
import addorEdit from './empDialog.vue'
import assignRole from './assignRole.vue'
export default {
  components: {
    addorEdit,
    assignRole
  },
  data() {
    return {
      list: [],
      showDialog: false,
      RoleshowDialog: false,
      pageNumber: 1,
      queryParams: {
        page: 1,
        size: 2
      },
      curPage: 1,
      curId: 0,
      page: 1, // 当前页码
      size: 2, // 每页几条
      total: 0 // 总共数据条数
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    async loadEmployees() {
      const res = await getEmployeeList(this.queryParams)
      // res.data.rows.forEach(item => {
      //   item.timeOfEntry.slice(0, 10)
      // })
      this.list = res.data.rows
      this.total = res.data.total
      // this.size = this.total
      this.curPage = this.queryParams.page
      console.log(this.list)
      this.pageFn()
    },
    format(val) {
      return EmployFormatMap[val] || '未知'
    },
    // 会自动接收当前点击的页码
    hCurrentChange(curPage) {
      // alert(curPage)
      // 1. 更新页码
      this.queryParams.page = curPage
      // 2. 重发请求
      this.loadEmployees()
    },
    // 每页几条
    hSizeChange(curSize) {
      // alert(curSize)
      // 1. 更新每页的条数
      this.queryParams.size = curSize
      // 2. 重发请求
      this.loadEmployees()
    },
    // 删除功能
    async doDel(id) {
      await delEmployee(id)
      // 当页面剩一条数据时执行删除数据这个功能，判断一下让page减一，这样重新渲染出来的页面就是上一页的数据了
      if (this.list.length === 1) {
        this.queryParams.page--
        // 当删除到第一页时剩一条数据了，再减少page就成-1了所以这里要判断一下
        if (this.queryParams.page <= 0) {
          this.queryParams.page = 1
        }
      }
      // 删除后重新渲染页面
      this.loadEmployees()
    },
    hDel(id) {
      this.$confirm('确认删除吗')
        .then(() => {
          // const MaxPage = Math.ceil(this.total / this.queryParams.size)
          this.doDel(id)
        })
        .catch(() => {})
    },
    hUpdate() {
      this.showDialog = false
      if (this.total % this.queryParams.size === 0) {
        this.queryParams.page = this.total / this.queryParams.size + 1
      } else {
        // 最后一页的页码
        this.queryParams.page = Math.floor(this.total / this.queryParams.size) + 1
      }
      this.loadEmployees()
    },
    hCloseDialog() {
      this.showDialog = false
      this.$refs.AddEmployee.resetForm()
      console.log('重置运行成功')
    },
    // 序号按顺序排，先找出每页第一个序号是几，然后再依次加index下标值这样就实现了按需排号
    pageFn() {
      const pageNumber = this.queryParams.page * this.queryParams.size - this.queryParams.size + 1
      this.pageNumber = pageNumber
      this.list.forEach((item, index) => {
        return index === 0 ? (item.page = this.pageNumber) : (item.page = this.pageNumber + index)
      })
      console.log('list', this.list)
    },
    // 格式化返回的数据
    transformDate(res) {
      const mapInfo = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      // 从后台数据中取出属性名
      const key = Object.keys(res[0])
      // mapInfo[item]是从对象上用key取值
      const header = key.map(item => mapInfo[item])
      // 从后台数据中取出属性值
      const value = res.map(item => Object.values(item))
      // Object.values(item) 一个对象产生一个数组,map还返回一个数组,就形成了二维数组
      console.log('取出的属性名', key)
      return { header, value }
    },
    // 导出功能
    async expendFn() {
      // const res = await getEmployeeList(this.page, this.size)
      await this.loadEmployees()
      const { header, value } = this.transformDate(this.list)
      console.log('取出的后台数据', this.list, header, value)
      // 当我们点击导出后才加载导出模块
      import('@/vendor/Export2Excel').then(excel => {
        // excle表示导入的模块对象
        excel.export_json_to_excel({
          header: header, // 表头 必填
          // data必须是二维数组
          data: value, // 具体数据必备
          filename: '员工数据', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 分配角色
    AddRoles(id) {
      // 打开弹窗
      this.RoleshowDialog = true
      // 更新id
      this.curId = id
      console.log(id)
      // 打开弹窗将程序延迟到数据请求完后执行
      this.$nextTick(() => {
        this.$refs.assignRole.loadRolesById()
      })
      // this.$nextTick(() => {
      //   // 3. 找到子组件，调用loadRolesById获取用户角色并回填
      //   this.$refs.assignRole.loadRolesById()
      // })
    },
    // 子组件成功更新角色数据
    hUpdateRoleSuccess() {
      // 1. 关闭弹层
      this.RoleshowDialog = false
      // 2. 更新数据
      this.loadEmployees()
    }
  }
}
</script>

